/*
 * Copyright 2009, 2010, YUNNAN Co-soft Information Technology Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Description: Language.
 * Version: 1.0.1.2, May 31, 2010
 * Author: Liang Ding
 */
function changeLocale(newLocale) {
    var requestJSONObject = {
        "locale": newLocale
    };

    jsonRpc.languageService.getLabels(changeLocaleCallback, requestJSONObject);

    locale = newLocale;
}

function changeLocaleCallback(result, error) {
    if (error) {
        alert("Error: " + JSON.stringify(error));

        return;
    }

    if ("CHANGE_LOCALE_SUCC" === result.sc) {
        for (var i = 0; i < result.labels.length; i++) {
            var id = result.labels[i].labelId;
            if (id === "htmlTitle") { // use function labelHtmlTitle to label <title> element
                continue;
            }

            var text = result.labels[i].labelText;
            var $labels = $("." + id + "Label");

            if (undefined === $labels[0]) {
                continue;
            }

            label($labels, text);
        }

        labelHtmlTitle(result.htmlTitle);
        clearContactUsHints();
    } else {
        alert(result.msgs.localeNotFound); // XXX: do not use alert for error message
    }
}

function label($labels, text) {
    for (var i = 0; i < $labels.length; i++) {
        switch ($labels[i].tagName.toLowerCase()) {
            case "div":
            case "img":
                $($labels[i]).attr("title", text);
                break;
            default:
                $($labels[i]).html(text);
                break;
        }
    }
}

function labelHtmlTitle(htmlTitle) {
    document.title = htmlTitle;
}

function getLocale() {
    var language = navigator.language ? navigator.language : navigator.browserLanguage;
    var lang = language.split("-")[0];
    var country = language.split("-")[1];

    return lang.toLowerCase() + "_" + country.toUpperCase();
}
